package com.my.study.lock;

import com.my.study.util.CountDownLatchUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch:用于倒计时(10减到0的过程),每一个线程执行完成减1
 *
 * 当所有子线程执行完成,数字减到0,执行主线程
 */
public class CountDownLatchDemo {

    private final static int NUM = 10;

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        //simpleTest();
        testApplication();
    }

    /**
     * 简单应用
     *
     * @throws InterruptedException
     */
    private static void simpleTest() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(NUM);
        for (int i = 0; i < NUM; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"\t 执行完成");
                countDownLatch.countDown();
            },"t"+i).start();
        }
        countDownLatch.await();
        System.out.println("所有线程执行完成,main线程打印日志");
    }

    /**
     * 开发过程应用
     *
     * @throws BrokenBarrierException
     * @throws InterruptedException
     */
    private static void testApplication() throws BrokenBarrierException, InterruptedException {
        // 开发过程应用
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < 25; i++) {
            ids.add("id"+i);
        }
        String result = CountDownLatchUtil.executorMainTask(5, ids, strings -> {
            strings.forEach(System.out::println);
            return strings;
        });
        System.out.println(result);
    }
}
